<!DOCTYPE html>


<html lang="en">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="小人物,码农" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    第六章 初始化和清理 |  歆雨小屋
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="歆雨小屋" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-第六章 初始化和清理"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  第六章 初始化和清理
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/07/27/%E7%AC%AC%E5%85%AD%E7%AB%A0%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%92%8C%E6%B8%85%E7%90%86/" class="article-date">
  <time datetime="2020-07-27T14:26:31.000Z" itemprop="datePublished">2020-07-27</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/">Java编程思想</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">18.3k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">72 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <!-- Housekeeping -->

<p>“不安全”的编程是造成编程代价昂贵的罪魁祸首之一。有两个安全性问题：初始化和清理。C 语言中很多的 bug 都是因为程序员忘记初始化导致的。尤其是很多类库的使用者不知道如何初始化类库组件，甚至他们必须得去初始化。清理则是另一个特殊的问题，因为当你使用一个元素做完事后就不会去关心这个元素，所以你很容易忘记清理它。这样就造成了元素使用的资源滞留不会被回收，直到程序消耗完所有的资源（特别是内存）。</p>
<p>C++ 引入了构造器的概念，这是一个特殊的方法，每创建一个对象，这个方法就会被自动调用。Java 采用了构造器的概念，另外还使用了垃圾收集器（Garbage Collector, GC）去自动回收不再被使用的对象所占的资源。这一章将讨论初始化和清理的问题，以及在 Java 中对它们的支持。</p>
<a id="more"></a>
<!-- Guaranteed Initialization with the Constructor -->

<h2 id="利用构造器保证初始化"><a href="#利用构造器保证初始化" class="headerlink" title="利用构造器保证初始化"></a>利用构造器保证初始化</h2><p>你可能想为每个类创建一个 <code>initialize()</code> 方法，该方法名暗示着在使用类之前需要先调用它。不幸的是，用户必须得记得去调用它。在 Java 中，类的设计者通过构造器保证每个对象的初始化。如果一个类有构造器，那么 Java 会在用户使用对象之前（即对象刚创建完成）自动调用对象的构造器方法，从而保证初始化。下个挑战是如何命名构造器方法。存在两个问题：第一个是任何命名都可能与类中其他已有元素的命名冲突；第二个是编译器必须始终知道构造器方法名称，从而调用它。C++ 的解决方法看起来是最简单且最符合逻辑的，所以 Java 中使用了同样的方式：构造器名称与类名相同。在初始化过程中自动调用构造器方法是有意义的。</p>
<p>以下示例是包含了一个构造器的类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/SimpleConstructor.java</span></span><br><span class="line"><span class="comment">// Demonstration of a simple constructor</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Rock</span> </span>&#123;</span><br><span class="line">    Rock() &#123; <span class="comment">// 这是一个构造器</span></span><br><span class="line">        System.out.print(<span class="string">"Rock "</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleConstructor</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span> Rock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Rock Rock Rock Rock Rock Rock Rock Rock Rock Rock</span><br></pre></td></tr></table></figure>

<p>现在，当创建一个对象时：<code>new Rock()</code> ，内存被分配，构造器被调用。构造器保证了对象在你使用它之前进行了正确的初始化。</p>
<p>有一点需要注意，构造器方法名与类名相同，不需要符合首字母小写的编程风格。在 C++ 中，无参构造器被称为默认构造器，这个术语在 Java 出现之前使用了很多年。但是，出于一些原因，Java 设计者们决定使用无参构造器这个名称，我（作者）认为这种叫法笨拙而且没有必要，所以我打算继续使用默认构造器。Java 8 引入了 <strong>default</strong> 关键字修饰方法，所以算了，我还是用无参构造器的叫法吧。</p>
<p>跟其他方法一样，构造器方法也可以传入参数来定义如何创建一个对象。之前的例子稍作修改，使得构造器接收一个参数：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/SimpleConstructor2.java</span></span><br><span class="line"><span class="comment">// Constructors can have arguments</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Rock2</span> </span>&#123;</span><br><span class="line">    Rock2(<span class="keyword">int</span> i) &#123;</span><br><span class="line">        System.out.print(<span class="string">"Rock "</span> + i + <span class="string">" "</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleConstructor2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span> Rock2(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Rock <span class="number">0</span> Rock <span class="number">1</span> Rock <span class="number">2</span> Rock <span class="number">3</span> Rock <span class="number">4</span> Rock <span class="number">5</span> Rock <span class="number">6</span> Rock <span class="number">7</span></span><br></pre></td></tr></table></figure>

<p>如果类 <strong>Tree</strong> 有一个构造方法，只接收一个参数用来表示树的高度，那么你可以像下面这样创建一棵树:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Tree t = <span class="keyword">new</span> Tree(<span class="number">12</span>); <span class="comment">// 12-foot 树</span></span><br></pre></td></tr></table></figure>

<p>如果 <strong>Tree(int)</strong> 是唯一的构造器，那么编译器就不允许你以其他任何方式创建 <strong>Tree</strong> 类型的对象。</p>
<p>构造器消除了一类重要的问题，使得代码更易读。例如，在上面的代码块中，你看不到对 <code>initialize()</code> 方法的显式调用，而从概念上来看，<code>initialize()</code> 方法应该与对象的创建分离。在 Java 中，对象的创建与初始化是统一的概念，二者不可分割。</p>
<p>构造器没有返回值，它是一种特殊的方法。但它和返回类型为 <code>void</code> 的普通方法不同，普通方法可以返回空值，你还能选择让它返回别的类型；而构造器没有返回值，却同时也没有给你选择的余地（<code>new</code> 表达式虽然返回了刚创建的对象的引用，但构造器本身却没有返回任何值）。如果它有返回值，并且你也可以自己选择让它返回什么，那么编译器就还得知道接下来该怎么处理那个返回值（这个返回值没有接收者）。</p>
<!-- Method Overloading -->

<h2 id="方法重载"><a href="#方法重载" class="headerlink" title="方法重载"></a>方法重载</h2><p>任何编程语言中都具备的一项重要特性就是命名。当你创建一个对象时，就会给此对象分配的内存空间命名。方法是行为的命名。你通过名字指代所有的对象，属性和方法。良好命名的系统易于理解和修改。就好比写散文——目的是与读者沟通。</p>
<p>将人类语言细微的差别映射到编程语言中会产生一个问题。通常，相同的词可以表达多种不同的含义——它们被”重载”了。特别是当含义的差别很小时，这会更加有用。你会说”清洗衬衫”、”清洗车”和”清洗狗”。而如果硬要这么说就会显得很愚蠢：”以洗衬衫的方式洗衬衫”、”以洗车的方式洗车”和”以洗狗的方式洗狗”，因为听众根本不需要区分行为的动作。大多数人类语言都具有”冗余”性，所以即使漏掉几个词，你也能明白含义。你不需要对每个概念都使用不同的词汇——可以从上下文推断出含义。</p>
<p>大多数编程语言（尤其是 C 语言）要求为每个方法（在这些语言中经常称为函数）提供一个独一无二的标识符。所以，你不能有一个 <code>print()</code> 函数既能打印整型，也能打印浮点型——每个函数名都必须不同。</p>
<p>在 Java (C++) 中，还有一个因素也促使了必须使用方法重载：构造器。因为构造器方法名肯定是与类名相同，所以一个类中只会有一个构造器名。那么你怎么通过不同的方式创建一个对象呢？例如，你想创建一个类，这个类的初始化方式有两种：一种是标准化方式，另一种是从文件中读取信息的方式。你需要两个构造器：无参构造器和有一个 <strong>String</strong> 类型参数的构造器，该参数传入文件名。两个构造器具有相同的名字——与类名相同。因此，方法重载是必要的，它允许方法具有相同的方法名但接收的参数不同。尽管方法重载对于构造器是重要的，但是也可以对任何方法很方便地进行重载。</p>
<p>下例展示了如何重载构造器和方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Overloading.java</span></span><br><span class="line"><span class="comment">// Both constructor and ordinary method overloading</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tree</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> height;</span><br><span class="line">    Tree() &#123;</span><br><span class="line">        System.out.println(<span class="string">"Planting a seedling"</span>);</span><br><span class="line">        height = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    Tree(<span class="keyword">int</span> initialHeight) &#123;</span><br><span class="line">        height = initialHeight;</span><br><span class="line">        System.out.println(<span class="string">"Creating new Tree that is "</span> + height + <span class="string">" feet tall"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">info</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Tree is "</span> + height + <span class="string">" feet tall"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">info</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        System.out.println(s + <span class="string">": Tree is "</span> + height + <span class="string">" feet tall"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Overloading</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">            Tree t = <span class="keyword">new</span> Tree(i);</span><br><span class="line">            t.info();</span><br><span class="line">            t.info(<span class="string">"overloaded method"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">new</span> Tree(); </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Creating <span class="keyword">new</span> Tree that is <span class="number">0</span> feet tall</span><br><span class="line">Tree is <span class="number">0</span> feet tall</span><br><span class="line">overloaded method: Tree is <span class="number">0</span> feet tall</span><br><span class="line">Creating <span class="keyword">new</span> Tree that is <span class="number">1</span> feet tall</span><br><span class="line">Tree is <span class="number">1</span> feet tall</span><br><span class="line">overloaded method: Tree is <span class="number">1</span> feet tall</span><br><span class="line">Creating <span class="keyword">new</span> Tree that is <span class="number">2</span> feet tall</span><br><span class="line">Tree is <span class="number">2</span> feet tall</span><br><span class="line">overloaded method: Tree is <span class="number">2</span> feet tall</span><br><span class="line">Creating <span class="keyword">new</span> Tree that is <span class="number">3</span> feet tall</span><br><span class="line">Tree is <span class="number">3</span> feet tall</span><br><span class="line">overloaded method: Tree is <span class="number">3</span> feet tall</span><br><span class="line">Creating <span class="keyword">new</span> Tree that is <span class="number">4</span> feet tall</span><br><span class="line">Tree is <span class="number">4</span> feet tall</span><br><span class="line">overloaded method: Tree is <span class="number">4</span> feet tall</span><br><span class="line">Planting a seedling</span><br></pre></td></tr></table></figure>

<p>一个 <strong>Tree</strong> 对象既可以是一颗树苗，使用无参构造器创建，也可以是一颗在温室中已长大的树，已经有一定高度，这时候，就需要使用有参构造器创建。</p>
<p>你也许想以多种方式调用 <code>info()</code> 方法。比如，如果你想打印额外的消息，就可以使用 <code>info(String)</code> 方法。如果你无话可说，就可以使用 <code>info()</code> 方法。用两个命名定义完全相同的概念看起来很奇怪，而使用方法重载，你就可以使用一个命名来定义一个概念。</p>
<h3 id="区分重载方法"><a href="#区分重载方法" class="headerlink" title="区分重载方法"></a>区分重载方法</h3><p>如果两个方法命名相同，Java是怎么知道你调用的是哪个呢？有一条简单的规则：每个被重载的方法必须有独一无二的参数列表。你稍微思考下，就会很明了了，除了通过参数列表的不同来区分两个相同命名的方法，其他也没什么方式了。你甚至可以根据参数列表中的参数顺序来区分不同的方法，尽管这会造成代码难以维护。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/OverloadingOrder.java</span></span><br><span class="line"><span class="comment">// Overloading based on the order of the arguments</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OverloadingOrder</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(String s, <span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"String: "</span> + s + <span class="string">", int: "</span> + i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">int</span> i, String s)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"int: "</span> + i + <span class="string">", String: "</span> + s);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        f(<span class="string">"String first"</span>, <span class="number">1</span>);</span><br><span class="line">        f(<span class="number">99</span>, <span class="string">"Int first"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String: String first, <span class="keyword">int</span>: <span class="number">1</span></span><br><span class="line"><span class="keyword">int</span>: <span class="number">99</span>, String: Int first</span><br></pre></td></tr></table></figure>

<p>两个 <code>f()</code> 方法具有相同的参数，但是参数顺序不同，根据这个就可以区分它们。</p>
<h3 id="重载与基本类型"><a href="#重载与基本类型" class="headerlink" title="重载与基本类型"></a>重载与基本类型</h3><p>基本类型可以自动从较小的类型转型为较大的类型。当这与重载结合时，这会令人有点困惑，下面是一个这样的例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/PrimitiveOverloading.java</span></span><br><span class="line"><span class="comment">// Promotion of primitives and overloading</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrimitiveOverloading</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">char</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f1(char)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">byte</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f1(byte)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">short</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f1(short)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f1(int)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">long</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f1(long)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">float</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f1(float)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">double</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f1(double)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(<span class="keyword">byte</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f2(byte)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(<span class="keyword">short</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f2(short)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(<span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f2(int)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(<span class="keyword">long</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f2(long)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(<span class="keyword">float</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f2(float)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(<span class="keyword">double</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f2(double)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f3</span><span class="params">(<span class="keyword">short</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f3(short)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f3</span><span class="params">(<span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f3(int)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f3</span><span class="params">(<span class="keyword">long</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f3(long)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f3</span><span class="params">(<span class="keyword">float</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f3(float)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f3</span><span class="params">(<span class="keyword">double</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f3(double)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f4</span><span class="params">(<span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f4(int)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f4</span><span class="params">(<span class="keyword">long</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f4(long)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f4</span><span class="params">(<span class="keyword">float</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f4(float)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f4</span><span class="params">(<span class="keyword">double</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f4(double)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f5</span><span class="params">(<span class="keyword">long</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f5(long)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f5</span><span class="params">(<span class="keyword">float</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f5(float)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f5</span><span class="params">(<span class="keyword">double</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f5(double)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f6</span><span class="params">(<span class="keyword">float</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f6(float)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f6</span><span class="params">(<span class="keyword">double</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f6(double)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f7</span><span class="params">(<span class="keyword">double</span> x)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"f7(double)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">testConstVal</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"5: "</span>);</span><br><span class="line">        f1(<span class="number">5</span>);f2(<span class="number">5</span>);f3(<span class="number">5</span>);f4(<span class="number">5</span>);f5(<span class="number">5</span>);f6(<span class="number">5</span>);f7(<span class="number">5</span>);</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">testChar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">char</span> x = <span class="string">'x'</span>;</span><br><span class="line">        System.out.print(<span class="string">"char: "</span>);</span><br><span class="line">        f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">testByte</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span> x = <span class="number">0</span>;</span><br><span class="line">        System.out.print(<span class="string">"byte: "</span>);</span><br><span class="line">        f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">testShort</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">short</span> x = <span class="number">0</span>;</span><br><span class="line">        System.out.print(<span class="string">"short: "</span>);</span><br><span class="line">        f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">testInt</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> x = <span class="number">0</span>;</span><br><span class="line">        System.out.print(<span class="string">"int: "</span>);</span><br><span class="line">        f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">testLong</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> x = <span class="number">0</span>;</span><br><span class="line">        System.out.print(<span class="string">"long: "</span>);</span><br><span class="line">        f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">testFloat</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">float</span> x = <span class="number">0</span>;</span><br><span class="line">        System.out.print(<span class="string">"float: "</span>);</span><br><span class="line">        f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">testDouble</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">double</span> x = <span class="number">0</span>;</span><br><span class="line">        System.out.print(<span class="string">"double: "</span>);</span><br><span class="line">        f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        PrimitiveOverloading p = <span class="keyword">new</span> PrimitiveOverloading();</span><br><span class="line">        p.testConstVal();</span><br><span class="line">        p.testChar();</span><br><span class="line">        p.testByte();</span><br><span class="line">        p.testShort();</span><br><span class="line">        p.testInt();</span><br><span class="line">        p.testLong();</span><br><span class="line">        p.testFloat();</span><br><span class="line">        p.testDouble();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">5</span>: f1(<span class="keyword">int</span>)f2(<span class="keyword">int</span>)f3(<span class="keyword">int</span>)f4(<span class="keyword">int</span>)f5(<span class="keyword">long</span>)f6(<span class="keyword">float</span>)f7(<span class="keyword">double</span>)</span><br><span class="line"><span class="keyword">char</span>: f1(<span class="keyword">char</span>)f2(<span class="keyword">int</span>)f3(<span class="keyword">int</span>)f4(<span class="keyword">int</span>)f5(<span class="keyword">long</span>)f6(<span class="keyword">float</span>)f7(<span class="keyword">double</span>)</span><br><span class="line"><span class="keyword">byte</span>: f1(<span class="keyword">byte</span>)f2(<span class="keyword">byte</span>)f3(<span class="keyword">short</span>)f4(<span class="keyword">int</span>)f5(<span class="keyword">long</span>)f6(<span class="keyword">float</span>)f7(<span class="keyword">double</span>)</span><br><span class="line"><span class="keyword">short</span>: f1(<span class="keyword">short</span>)f2(<span class="keyword">short</span>)f3(<span class="keyword">short</span>)f4(<span class="keyword">int</span>)f5(<span class="keyword">long</span>)f6(<span class="keyword">float</span>)f7(<span class="keyword">double</span>)</span><br><span class="line"><span class="keyword">int</span>: f1(<span class="keyword">int</span>)f2(<span class="keyword">int</span>)f3(<span class="keyword">int</span>)f4(<span class="keyword">int</span>)f5(<span class="keyword">long</span>)f6(<span class="keyword">float</span>)f7(<span class="keyword">double</span>)</span><br><span class="line"><span class="keyword">long</span>: f1(<span class="keyword">long</span>)f2(<span class="keyword">long</span>)f3(<span class="keyword">long</span>)f4(<span class="keyword">long</span>)f5(<span class="keyword">long</span>)f6(<span class="keyword">float</span>)f7(<span class="keyword">double</span>)</span><br><span class="line"><span class="keyword">float</span>: f1(<span class="keyword">float</span>)f2(<span class="keyword">float</span>)f3(<span class="keyword">float</span>)f4(<span class="keyword">float</span>)f5(<span class="keyword">float</span>)f6(<span class="keyword">float</span>)f7(<span class="keyword">double</span>)</span><br><span class="line"><span class="keyword">double</span>: f1(<span class="keyword">double</span>)f2(<span class="keyword">double</span>)f3(<span class="keyword">double</span>)f4(<span class="keyword">double</span>)f5(<span class="keyword">double</span>)f6(<span class="keyword">double</span>)f7(<span class="keyword">double</span>)</span><br></pre></td></tr></table></figure>

<p>如果传入的参数类型大于方法期望接收的参数类型，你必须首先做下转换，如果你不做的话，编译器就会报错。</p>
<h3 id="返回值的重载"><a href="#返回值的重载" class="headerlink" title="返回值的重载"></a>返回值的重载</h3><p>经常会有人困惑，”为什么只能通过方法名和参数列表，不能通过方法名和返回值区分方法呢?”。例如以下两个方法，它们有相同的命名和参数，但是很容易区分：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">f</span><span class="params">()</span> </span>&#123;<span class="keyword">return</span> <span class="number">1</span>;&#125;</span><br></pre></td></tr></table></figure>

<p>有些情况下，编译器很容易就可以从上下文准确推断出该调用哪个方法，如 <code>int x = f()</code>。</p>
<p>但是，你可以调用一个方法且忽略返回值。这叫做调用一个函数的副作用，因为你不在乎返回值，只是想利用方法做些事。所以如果你直接调用 <code>f()</code>，Java 编译器就不知道你想调用哪个方法，阅读者也不明所以。因为这个原因，所以你不能根据返回值类型区分重载的方法。为了支持新特性，Java 8 在一些具体情形下提高了猜测的准确度，但是通常来说并不起作用。</p>
<!-- No-arg Constructors -->

<h2 id="无参构造器"><a href="#无参构造器" class="headerlink" title="无参构造器"></a>无参构造器</h2><p>如前文所说，一个无参构造器就是不接收参数的构造器，用来创建一个”默认的对象”。如果你创建一个类，类中没有构造器，那么编译器就会自动为你创建一个无参构造器。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/DefaultConstructor.java</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bird</span> </span>&#123;&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultConstructor</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Bird bird = <span class="keyword">new</span> Bird(); <span class="comment">// 默认的</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>表达式 <code>new Bird()</code> 创建了一个新对象，调用了无参构造器，尽管在 <strong>Bird</strong> 类中并没有显式的定义无参构造器。试想如果没有构造器，我们如何创建一个对象呢。但是,一旦你显式地定义了构造器（无论有参还是无参），编译器就不会自动为你创建无参构造器。如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/NoSynthesis.java</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bird2</span> </span>&#123;</span><br><span class="line">    Bird2(<span class="keyword">int</span> i) &#123;&#125;</span><br><span class="line">    Bird2(<span class="keyword">double</span> d) &#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NoSynthesis</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//- Bird2 b = new Bird2(); // No default</span></span><br><span class="line">        Bird2 b2 = <span class="keyword">new</span> Bird2(<span class="number">1</span>);</span><br><span class="line">        Bird2 b3 = <span class="keyword">new</span> Bird2(<span class="number">1.0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果你调用了 <code>new Bird2()</code> ，编译器会提示找不到匹配的构造器。当类中没有构造器时，编译器会说”你一定需要构造器，那么让我为你创建一个吧”。但是如果类中有构造器，编译器会说”你已经写了构造器了，所以肯定知道你在做什么，如果你没有创建默认构造器，说明你本来就不需要”。</p>
<!-- The this Keyword -->

<h2 id="this关键字"><a href="#this关键字" class="headerlink" title="this关键字"></a>this关键字</h2><p>对于两个相同类型的对象 <strong>a</strong> 和 <strong>b</strong>，你可能在想如何调用这两个对象的 <code>peel()</code> 方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/BananaPeel.java</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Banana</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">peel</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">        <span class="comment">/*...*/</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BananaPeel</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Banana a = <span class="keyword">new</span> Banana(), b = <span class="keyword">new</span> Banana();</span><br><span class="line">        a.peel(<span class="number">1</span>);</span><br><span class="line">        b.peel(<span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果只有一个方法 <code>peel()</code> ，那么怎么知道调用的是对象 <strong>a</strong> 的 <code>peel()</code>方法还是对象 <strong>b</strong> 的 <code>peel()</code> 方法呢？编译器做了一些底层工作，所以你可以像这样编写代码。<code>peel()</code> 方法中第一个参数隐密地传入了一个指向操作对象的</p>
<p>引用。因此，上述例子中的方法调用像下面这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Banana.peel(a, <span class="number">1</span>)</span><br><span class="line">Banana.peel(b, <span class="number">2</span>)</span><br></pre></td></tr></table></figure>

<p>这是在内部实现的，你不可以直接这么编写代码，编译器不会接受，但能说明到底发生了什么。假设现在在方法内部，你想获得对当前对象的引用。但是，对象引用是被秘密地传达给编译器——并不在参数列表中。方便的是，有一个关键字: <strong>this</strong> 。<strong>this</strong> 关键字只能在非静态方法内部使用。当你调用一个对象的方法时，<strong>this</strong> 生成了一个对象引用。你可以像对待其他引用一样对待这个引用。如果你在一个类的方法里调用其他该类中的方法，不要使用 <strong>this</strong>，直接调用即可，<strong>this</strong> 自动地应用于其他方法上了。因此你可以像这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Apricot.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Apricot</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">pick</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">/* ... */</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">pit</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        pick();</span><br><span class="line">        <span class="comment">/* ... */</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 <code>pit()</code> 方法中，你可以使用 <code>this.pick()</code>，但是没有必要。编译器自动为你做了这些。<strong>this</strong> 关键字只用在一些必须显式使用当前对象引用的特殊场合。例如，用在 <strong>return</strong> 语句中返回对当前对象的引用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Leaf.java</span></span><br><span class="line"><span class="comment">// Simple use of the "this" keyword</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Leaf</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">Leaf <span class="title">increment</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        i++;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">print</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"i = "</span> + i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Leaf x = <span class="keyword">new</span> Leaf();</span><br><span class="line">        x.increment().increment().increment().print();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">i &#x3D; 3</span><br></pre></td></tr></table></figure>

<p>因为 <code>increment()</code> 通过 <strong>this</strong> 关键字返回当前对象的引用，因此在相同的对象上可以轻易地执行多次操作。</p>
<p><strong>this</strong> 关键字在向其他方法传递当前对象时也很有用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/PassingThis.java</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">eat</span><span class="params">(Apple apple)</span> </span>&#123;</span><br><span class="line">        Apple peeled = apple.getPeeled();</span><br><span class="line">        System.out.println(<span class="string">"Yummy"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Peeler</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> Apple <span class="title">peel</span><span class="params">(Apple apple)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// ... remove peel</span></span><br><span class="line">        <span class="keyword">return</span> apple; <span class="comment">// Peeled</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Apple</span> </span>&#123;</span><br><span class="line">    <span class="function">Apple <span class="title">getPeeled</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Peeler.peel(<span class="keyword">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PassingThis</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> Person().eat(<span class="keyword">new</span> Apple());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Yummy</span><br></pre></td></tr></table></figure>

<p><strong>Apple</strong> 因为某些原因（比如说工具类中的方法在多个类中重复出现，你不想代码重复），必须调用一个外部工具方法 <code>Peeler.peel()</code> 做一些行为。必须使用 <strong>this</strong> 才能将自身传递给外部方法。</p>
<h3 id="在构造器中调用构造器"><a href="#在构造器中调用构造器" class="headerlink" title="在构造器中调用构造器"></a>在构造器中调用构造器</h3><p>当你在一个类中写了多个构造器，有时你想在一个构造器中调用另一个构造器来避免代码重复。你通过 <strong>this</strong> 关键字实现这样的调用。</p>
<p>通常当你说 <strong>this</strong>，意味着”这个对象”或”当前对象”，它本身生成对当前对象的引用。在一个构造器中，当你给 <strong>this</strong> 一个参数列表时，它是另一层意思。它通过最直接的方式显式地调用匹配参数列表的构造器：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Flower.java</span></span><br><span class="line"><span class="comment">// Calling constructors with "this"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Flower</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> petalCount = <span class="number">0</span>;</span><br><span class="line">    String s = <span class="string">"initial value"</span>;</span><br><span class="line"></span><br><span class="line">    Flower(<span class="keyword">int</span> petals) &#123;</span><br><span class="line">        petalCount = petals;</span><br><span class="line">        System.out.println(<span class="string">"Constructor w/ int arg only, petalCount = "</span> + petalCount);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Flower(String ss) &#123;</span><br><span class="line">        System.out.println(<span class="string">"Constructor w/ string arg only, s = "</span> + ss);</span><br><span class="line">        s = ss;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Flower(String s, <span class="keyword">int</span> petals) &#123;</span><br><span class="line">        <span class="keyword">this</span>(petals);</span><br><span class="line">        <span class="comment">//- this(s); // Can't call two!</span></span><br><span class="line">        <span class="keyword">this</span>.s = s; <span class="comment">// Another use of "this"</span></span><br><span class="line">        System.out.println(<span class="string">"String &amp; int args"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Flower() &#123;</span><br><span class="line">        <span class="keyword">this</span>(<span class="string">"hi"</span>, <span class="number">47</span>);</span><br><span class="line">        System.out.println(<span class="string">"no-arg constructor"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">printPetalCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//- this(11); // Not inside constructor!</span></span><br><span class="line">        System.out.println(<span class="string">"petalCount = "</span> + petalCount + <span class="string">" s = "</span> + s);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Flower x = <span class="keyword">new</span> Flower();</span><br><span class="line">        x.printPetalCount();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Constructor w&#x2F; int arg only, petalCount &#x3D; 47</span><br><span class="line">String &amp; int args</span><br><span class="line">no-arg constructor</span><br><span class="line">petalCount &#x3D; 47 s &#x3D; hi</span><br></pre></td></tr></table></figure>

<p>从构造器 <code>Flower(String s, int petals)</code> 可以看出，其中只能通过 <strong>this</strong> 调用一次构造器。另外，必须首先调用构造器，否则编译器会报错。这个例子同样展示了 <strong>this</strong> 的另一个用法。参数列表中的变量名 <strong>s</strong> 和成员变量名 <strong>s</strong> 相同，会引起混淆。你可以通过 <code>this.s</code> 表明你指的是成员变量 <strong>s</strong>，从而避免重复。你经常会在 Java 代码中看到这种用法，同时本书中也会多次出现这种写法。在 <code>printPetalCount()</code> 方法中，编译器不允许你在一个构造器之外的方法里调用构造器。</p>
<h3 id="static-的含义"><a href="#static-的含义" class="headerlink" title="static 的含义"></a>static 的含义</h3><p>记住了 <strong>this</strong> 关键字的内容，你会对 <strong>static</strong> 修饰的方法有更加深入的理解：<strong>static</strong> 方法中不会存在 <strong>this</strong>。你不能在静态方法中调用非静态方法（反之可以）。静态方法是为类而创建的，不需要任何对象。事实上，这就是静态方法的主要目的，静态方法看起来就像全局方法一样，但是 Java 中不允许全局方法，一个类中的静态方法可以被其他的静态方法和静态属性访问。一些人认为静态方法不是面向对象的，因为它们的确具有全局方法的语义。使用静态方法，因为不存在 <strong>this</strong>，所以你没有向一个对象发送消息。的确，如果你发现代码中出现了大量的 <strong>static</strong> 方法，就该重新考虑自己的设计了。然而，<strong>static</strong> 的概念很实用，许多时候都要用到它。至于它是否真的”面向对象”，就留给理论家去讨论吧。</p>
<!-- Cleanup: Finalization and Garbage Collection -->

<h2 id="垃圾回收器"><a href="#垃圾回收器" class="headerlink" title="垃圾回收器"></a>垃圾回收器</h2><p>程序员都了解初始化的重要性，但通常会忽略清理的重要性。毕竟，谁会去清理一个 <strong>int</strong> 呢？但是使用完一个对象就不管它并非总是安全的。Java 中有垃圾回收器回收无用对象占用的内存。但现在考虑一种特殊情况：你创建的对象不是通过 <strong>new</strong> 来分配内存的，而垃圾回收器只知道如何释放用 <strong>new</strong> 创建的对象的内存，所以它不知道如何回收不是 <strong>new</strong> 分配的内存。为了处理这种情况，Java 允许在类中定义一个名为 <code>finalize()</code> 的方法。</p>
<p>它的工作原理”假定”是这样的：当垃圾回收器准备回收对象的内存时，首先会调用其 <code>finalize()</code> 方法，并在下一轮的垃圾回收动作发生时，才会真正回收对象占用的内存。所以如果你打算使用 <code>finalize()</code> ，就能在垃圾回收时做一些重要的清理工作。<code>finalize()</code> 是一个潜在的编程陷阱，因为一些程序员（尤其是 C++ 程序员）会一开始把它误认为是 C++ 中的析构函数（C++ 在销毁对象时会调用这个函数）。所以有必要明确区分一下：在 C++ 中，对象总是被销毁的（在一个 bug-free 的程序中），而在 Java 中，对象并非总是被垃圾回收，或者换句话说：</p>
<ol>
<li>对象可能不被垃圾回收。</li>
<li>垃圾回收不等同于析构。</li>
</ol>
<p>这意味着在你不再需要某个对象之前，如果必须执行某些动作，你得自己去做。Java 没有析构器或类似的概念，所以你必须得自己创建一个普通的方法完成这项清理工作。例如，对象在创建的过程中会将自己绘制到屏幕上。如果不是明确地从屏幕上将其擦除，它可能永远得不到清理。如果在 <code>finalize()</code> 方法中加入某种擦除功能，那么当垃圾回收发生时，<code>finalize()</code> 方法被调用（不保证一定会发生），图像就会被擦除，要是”垃圾回收”没有发生，图像则仍会保留下来。</p>
<p>也许你会发现，只要程序没有濒临内存用完的那一刻，对象占用的空间就总也得不到释放。如果程序执行结束，而垃圾回收器一直没有释放你创建的任何对象的内存，则当程序退出时，那些资源会全部交还给操作系统。这个策略是恰当的，因为垃圾回收本身也有开销，要是不使用它，那就不用支付这部分开销了。</p>
<h3 id="finalize-的用途"><a href="#finalize-的用途" class="headerlink" title="finalize() 的用途"></a><code>finalize()</code> 的用途</h3><p>如果你不能将 <code>finalize()</code> 作为通用的清理方法，那么这个方法有什么用呢？</p>
<p>这引入了要记住的第3点：</p>
<ol start="3">
<li>垃圾回收只与内存有关。</li>
</ol>
<p>也就是说，使用垃圾回收的唯一原因就是为了回收程序不再使用的内存。所以对于与垃圾回收有关的任何行为来说（尤其是 <code>finalize()</code> 方法），它们也必须同内存及其回收有关。</p>
<p>但这是否意味着如果对象中包括其他对象，<code>finalize()</code> 方法就应该明确释放那些对象呢？不是，无论对象是如何创建的，垃圾回收器都会负责释放对象所占用的所有内存。这就将对 <code>finalize()</code> 的需求限制到一种特殊情况，即通过某种创建对象方式之外的方式为对象分配了存储空间。不过，你可能会想，Java 中万物皆对象，这种情况怎么可能发生？</p>
<p>看起来之所以有 <code>finalize()</code> 方法，是因为在分配内存时可能采用了类似 C 语言中的做法，而非 Java 中的通常做法。这种情况主要发生在使用”本地方法”的情况下，本地方法是一种用 Java 语言调用非 Java 语言代码的形式（关于本地方法的讨论，见本书电子版第2版的附录B）。本地方法目前只支持 C 和 C++，但是它们可以调用其他语言写的代码，所以实际上可以调用任何代码。在非 Java 代码中，也许会调用 C 的 <code>malloc()</code> 函数系列来分配存储空间，而且除非调用 <code>free()</code> 函数，不然存储空间永远得不到释放，造成内存泄露。但是，<code>free()</code> 是 C 和 C++ 中的函数，所以你需要在 <code>finalize()</code> 方法里用本地方法调用它。</p>
<p>读到这里，你可能明白了不会过多使用 <code>finalize()</code> 方法。对，它确实不是进行普通的清理工作的合适场所。那么，普通的清理工作在哪里执行呢？</p>
<h3 id="你必须实施清理"><a href="#你必须实施清理" class="headerlink" title="你必须实施清理"></a>你必须实施清理</h3><p>要清理一个对象，用户必须在需要清理的时候调用执行清理动作的方法。这听上去相当直接，但却与 C++ 中的”析构函数”的概念稍有抵触。在 C++ 中，所有对象都会被销毁，或者说应该被销毁。如果在 C++ 中创建了一个局部对象（在栈上创建，在 Java 中不行），此时的销毁动作发生在以”右花括号”为边界的、此对象作用域的末尾处。如果对象是用 <strong>new</strong> 创建的（类似于 Java 中），那么当程序员调用 C++ 的 <strong>delete</strong> 操作符时（Java 中不存在），就会调用相应的析构函数。如果程序员忘记调用 <strong>delete</strong>，那么永远不会调用析构函数，这样就会导致内存泄露，对象的其他部分也不会得到清理。这种 bug 很难跟踪，也是让 C++ 程序员转向 Java 的一个主要因素。相反，在 Java 中，没有用于释放对象的 <strong>delete</strong>，因为垃圾回收器会帮助你释放存储空间。甚至可以肤浅地认为，正是由于垃圾回收的存在，使得 Java 没有析构函数。然而，随着学习的深入，你会明白垃圾回收器的存在并不能完全替代析构函数（而且绝对不能直接调用 <code>finalize()</code>，所以这也不是一种解决方案）。如果希望进行除释放存储空间之外的清理工作，还是得明确调用某个恰当的 Java 方法：这就等同于使用析构函数了，只是没有它方便。</p>
<p>记住，无论是”垃圾回收”还是”终结”，都不保证一定会发生。如果 Java 虚拟机（JVM）并未面临内存耗尽的情形，它可能不会浪费时间执行垃圾回收以恢复内存。</p>
<h3 id="终结条件"><a href="#终结条件" class="headerlink" title="终结条件"></a>终结条件</h3><p>通常，不能指望 <code>finalize()</code> ，你必须创建其他的”清理”方法，并明确地调用它们。所以看起来，<code>finalize()</code> 只对大部分程序员很难用到的一些晦涩内存清理里有用了。但是，<code>finalize()</code> 还有一个有趣的用法，它不依赖于每次都要对 <code>finalize()</code> 进行调用，这就是对象终结条件的验证。</p>
<p>当对某个对象不感兴趣时——也就是它将被清理了，这个对象应该处于某种状态，这种状态下它占用的内存可以被安全地释放掉。例如，如果对象代表了一个打开的文件，在对象被垃圾回收之前程序员应该关闭这个文件。只要对象中存在没有被适当清理的部分，程序就存在很隐晦的 bug。<code>finalize()</code> 可以用来最终发现这个情况，尽管它并不总是被调用。如果某次 <code>finalize()</code> 的动作使得 bug 被发现，那么就可以据此找出问题所在——这才是人们真正关心的。以下是个简单的例子，示范了 <code>finalize()</code> 的可能使用方式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/TerminationCondition.java</span></span><br><span class="line"><span class="comment">// Using finalize() to detect a object that</span></span><br><span class="line"><span class="comment">// hasn't been properly cleaned up</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> onjava.*;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span> </span>&#123;</span><br><span class="line">    <span class="keyword">boolean</span> checkedOut = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">    Book(<span class="keyword">boolean</span> checkOut) &#123;</span><br><span class="line">        checkedOut = checkOut;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">checkIn</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        checkedOut = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">finalize</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (checkedOut) &#123;</span><br><span class="line">            System.out.println(<span class="string">"Error: checked out"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// Normally, you'll also do this:</span></span><br><span class="line">        <span class="comment">// super.finalize(); // Call the base-class version</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TerminationCondition</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Book novel = <span class="keyword">new</span> Book(<span class="keyword">true</span>);</span><br><span class="line">        <span class="comment">// Proper cleanup:</span></span><br><span class="line">        novel.checkIn();</span><br><span class="line">        <span class="comment">// Drop the reference, forget to clean up:</span></span><br><span class="line">        <span class="keyword">new</span> Book(<span class="keyword">true</span>);</span><br><span class="line">        <span class="comment">// Force garbage collection &amp; finalization:</span></span><br><span class="line">        System.gc();</span><br><span class="line">        <span class="keyword">new</span> Nap(<span class="number">1</span>); <span class="comment">// One second delay</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Error: checked out</span><br></pre></td></tr></table></figure>

<p>本例的终结条件是：所有的 <strong>Book</strong> 对象在被垃圾回收之前必须被登记。但在 <code>main()</code> 方法中，有一本书没有登记。要是没有 <code>finalize()</code> 方法来验证终结条件，将会很难发现这个 bug。</p>
<p>你可能注意到使用了 <code>@Override</code>。<code>@</code> 意味着这是一个注解，注解是关于代码的额外信息。在这里，该注解告诉编译器这不是偶然地重定义在每个对象中都存在的 <code>finalize()</code> 方法——程序员知道自己在做什么。编译器确保你没有拼错方法名，而且确保那个方法存在于基类中。注解也是对读者的提醒，<code>@Override</code> 在 Java 5 引入，在 Java 7 中改善，本书通篇会出现。</p>
<p>注意，<code>System.gc()</code> 用于强制进行终结动作。但是即使不这么做，只要重复地执行程序（假设程序将分配大量的存储空间而导致垃圾回收动作的执行），最终也能找出错误的 <strong>Book</strong> 对象。</p>
<p>你应该总是假设基类版本的 <code>finalize()</code> 也要做一些重要的事情，使用 <strong>super</strong> 调用它，就像在 <code>Book.finalize()</code> 中看到的那样。本例中，它被注释掉了，因为它需要进行异常处理，而我们到现在还没有涉及到。</p>
<h3 id="垃圾回收器如何工作"><a href="#垃圾回收器如何工作" class="headerlink" title="垃圾回收器如何工作"></a>垃圾回收器如何工作</h3><p>如果你以前用过的语言，在堆上分配对象的代价十分高昂，你可能自然会觉得 Java 中所有对象（基本类型除外）在堆上分配的方式也十分高昂。然而，垃圾回收器能很明显地提高对象的创建速度。这听起来很奇怪——存储空间的释放影响了存储空间的分配，但这确实是某些 Java 虚拟机的工作方式。这也意味着，Java 从堆空间分配的速度可以和其他语言在栈上分配空间的速度相媲美。</p>
<p>例如，你可以把 C++ 里的堆想象成一个院子，里面每个对象都负责管理自己的地盘。一段时间后，对象可能被销毁，但地盘必须复用。在某些 Java 虚拟机中，堆的实现截然不同：它更像一个传送带，每分配一个新对象，它就向前移动一格。这意味着对象存储空间的分配速度特别快。Java 的”堆指针”只是简单地移动到尚未分配的区域，所以它的效率与 C++ 在栈上分配空间的效率相当。当然实际过程中，在簿记工作方面还有少量额外开销，但是这部分开销比不上查找可用空间开销大。</p>
<p>你可能意识到了，Java 中的堆并非完全像传送带那样工作。要是那样的话，势必会导致频繁的内存页面调度——将其移进移出硬盘，因此会显得需要拥有比实际需要更多的内存。页面调度会显著影响性能。最终，在创建了足够多的对象后，内存资源被耗尽。其中的秘密在于垃圾回收器的介入。当它工作时，一边回收内存，一边使堆中的对象紧凑排列，这样”堆指针”就可以很容易地移动到更靠近传送带的开始处，也就尽量避免了页面错误。垃圾回收器通过重新排列对象，实现了一种高速的、有无限空间可分配的堆模型。</p>
<p>要想理解 Java 中的垃圾回收，先了解其他系统中的垃圾回收机制将会很有帮助。一种简单但速度很慢的垃圾回收机制叫做<em>引用计数</em>。每个对象中含有一个引用计数器，每当有引用指向该对象时，引用计数加 1。当引用离开作用域或被置为 <strong>null</strong> 时，引用计数减 1。因此，管理引用计数是一个开销不大但是在程序的整个生命周期频繁发生的负担。垃圾回收器会遍历含有全部对象的列表，当发现某个对象的引用计数为 0 时，就释放其占用的空间（但是，引用计数模式经常会在计数为 0 时立即释放对象）。这个机制存在一个缺点：如果对象之间存在循环引用，那么它们的引用计数都不为 0，就会出现应该被回收但无法被回收的情况。对垃圾回收器而言，定位这样的循环引用所需的工作量极大。引用计数常用来说明垃圾回收的工作方式，但似乎从未被应用于任何一种 Java 虚拟机实现中。</p>
<p>在更快的策略中，垃圾回收器并非基于引用计数。它们依据的是：对于任意”活”的对象，一定能最终追溯到其存活在栈或静态存储区中的引用。这个引用链条可能会穿过数个对象层次，由此，如果从栈或静态存储区出发，遍历所有的引用，你将会发现所有”活”的对象。对于发现的每个引用，必须追踪它所引用的对象，然后是该对象包含的所有引用，如此反复进行，直到访问完”根源于栈或静态存储区的引用”所形成的整个网络。你所访问过的对象一定是”活”的。注意，这解决了对象间循环引用的问题，这些对象不会被发现，因此也就被自动回收了。</p>
<p>在这种方式下，Java 虚拟机采用了一种<em>自适应</em>的垃圾回收技术。至于如何处理找到的存活对象，取决于不同的 Java 虚拟机实现。其中有一种做法叫做停止-复制（stop-and-copy）。顾名思义，这需要先暂停程序的运行（不属于后台回收模式），然后将所有存活的对象从当前堆复制到另一个堆，没有复制的就是需要被垃圾回收的。另外，当对象被复制到新堆时，它们是一个挨着一个紧凑排列，然后就可以按照前面描述的那样简单、直接地分配新空间了。</p>
<p>当对象从一处复制到另一处，所有指向它的引用都必须修正。位于栈或静态存储区的引用可以直接被修正，但可能还有其他指向这些对象的引用，它们在遍历的过程中才能被找到（可以想象成一个表格，将旧地址映射到新地址）。</p>
<p>这种所谓的”复制回收器”效率低下主要因为两个原因。其一：得有两个堆，然后在这两个分离的堆之间来回折腾，得维护比实际需要多一倍的空间。某些 Java 虚拟机对此问题的处理方式是，按需从堆中分配几块较大的内存，复制动作发生在这些大块内存之间。</p>
<p>其二在于复制本身。一旦程序进入稳定状态之后，可能只会产生少量垃圾，甚至没有垃圾。尽管如此，复制回收器仍然会将所有内存从一处复制到另一处，这很浪费。为了避免这种状况，一些 Java 虚拟机会进行检查：要是没有新垃圾产生，就会转换到另一种模式（即”自适应”）。这种模式称为标记-清扫（mark-and-sweep），Sun 公司早期版本的 Java 虚拟机一直使用这种技术。对一般用途而言，”标记-清扫”方式速度相当慢，但是当你知道程序只会产生少量垃圾甚至不产生垃圾时，它的速度就很快了。</p>
<p>“标记-清扫”所依据的思路仍然是从栈和静态存储区出发，遍历所有的引用，找出所有存活的对象。但是，每当找到一个存活对象，就给对象设一个标记，并不回收它。只有当标记过程完成后，清理动作才开始。在清理过程中，没有标记的对象将被释放，不会发生任何复制动作。”标记-清扫”后剩下的堆空间是不连续的，垃圾回收器要是希望得到连续空间的话，就需要重新整理剩下的对象。</p>
<p>“停止-复制”指的是这种垃圾回收动作不是在后台进行的；相反，垃圾回收动作发生的同时，程序将会暂停。在 Oracle 公司的文档中会发现，许多参考文献将垃圾回收视为低优先级的后台进程，但是早期版本的 Java 虚拟机并不是这么实现垃圾回收器的。当可用内存较低时，垃圾回收器会暂停程序。同样，”标记-清扫”工作也必须在程序暂停的情况下才能进行。</p>
<p>如前文所述，这里讨论的 Java 虚拟机中，内存分配以较大的”块”为单位。如果对象较大，它会占用单独的块。严格来说，”停止-复制”要求在释放旧对象之前，必须先将所有存活对象从旧堆复制到新堆，这导致了大量的内存复制行为。有了块，垃圾回收器就可以把对象复制到废弃的块。每个块都有年代数来记录自己是否存活。通常，如果块在某处被引用，其年代数加 1，垃圾回收器会对上次回收动作之后新分配的块进行整理。这对处理大量短命的临时对象很有帮助。垃圾回收器会定期进行完整的清理动作——大型对象仍然不会复制（只是年代数会增加），含有小型对象的那些块则被复制并整理。Java 虚拟机会监视，如果所有对象都很稳定，垃圾回收的效率降低的话，就切换到”标记-清扫”方式。同样，Java 虚拟机会跟踪”标记-清扫”的效果，如果堆空间出现很多碎片，就会切换回”停止-复制”方式。这就是”自适应”的由来，你可以给它个啰嗦的称呼：”自适应的、分代的、停止-复制、标记-清扫”式的垃圾回收器。</p>
<p>Java 虚拟机中有许多附加技术用来提升速度。尤其是与加载器操作有关的，被称为”即时”（Just-In-Time, JIT）编译器的技术。这种技术可以把程序全部或部分翻译成本地机器码，所以不需要 JVM 来进行翻译，因此运行得更快。当需要装载某个类（通常是创建该类的第一个对象）时，编译器会先找到其 <strong>.class</strong> 文件，然后将该类的字节码装入内存。你可以让即时编译器编译所有代码，但这种做法有两个缺点：一是这种加载动作贯穿整个程序生命周期内，累加起来需要花更多时间；二是会增加可执行代码的长度（字节码要比即时编译器展开后的本地机器码小很多），这会导致页面调度，从而一定降低程序速度。另一种做法称为<em>惰性评估</em>，意味着即时编译器只有在必要的时候才编译代码。这样，从未被执行的代码也许就压根不会被 JIT 编译。新版 JDK 中的 Java HotSpot 技术就采用了类似的做法，代码每被执行一次就优化一些，所以执行的次数越多，它的速度就越快。</p>
<!-- Member Initialization -->

<h2 id="成员初始化"><a href="#成员初始化" class="headerlink" title="成员初始化"></a>成员初始化</h2><p>Java 尽量保证所有变量在使用前都能得到恰当的初始化。对于方法的局部变量，这种保证会以编译时错误的方式呈现，所以如果写成：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">    i++;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你会得到一条错误信息，告诉你 <strong>i</strong> 可能尚未初始化。编译器可以为 <strong>i</strong> 赋一个默认值，但是未初始化的局部变量更有可能是程序员的疏忽，所以采用默认值反而会掩盖这种失误。强制程序员提供一个初始值，往往能帮助找出程序里的 bug。</p>
<p>要是类的成员变量是基本类型，情况就会变得有些不同。正如在”万物皆对象”一章中所看到的，类的每个基本类型数据成员保证都会有一个初始值。下面的程序可以验证这类情况，并显示它们的值：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/InitialValues.java</span></span><br><span class="line"><span class="comment">// Shows default initial values</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InitialValues</span> </span>&#123;</span><br><span class="line">    <span class="keyword">boolean</span> t;</span><br><span class="line">    <span class="keyword">char</span> c;</span><br><span class="line">    <span class="keyword">byte</span> b;</span><br><span class="line">    <span class="keyword">short</span> s;</span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">    <span class="keyword">long</span> l;</span><br><span class="line">    <span class="keyword">float</span> f;</span><br><span class="line">    <span class="keyword">double</span> d;</span><br><span class="line">    InitialValues reference;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">printInitialValues</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Data type Initial value"</span>);</span><br><span class="line">        System.out.println(<span class="string">"boolean "</span> + t);</span><br><span class="line">        System.out.println(<span class="string">"char["</span> + c + <span class="string">"]"</span>);</span><br><span class="line">        System.out.println(<span class="string">"byte "</span> + b);</span><br><span class="line">        System.out.println(<span class="string">"short "</span> + s);</span><br><span class="line">        System.out.println(<span class="string">"int "</span> + i);</span><br><span class="line">        System.out.println(<span class="string">"long "</span> + l);</span><br><span class="line">        System.out.println(<span class="string">"float "</span> + f);</span><br><span class="line">        System.out.println(<span class="string">"double "</span> + d);</span><br><span class="line">        System.out.println(<span class="string">"reference "</span> + reference);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> InitialValues().printInitialValues();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Data type Initial value</span><br><span class="line"><span class="keyword">boolean</span> <span class="keyword">false</span></span><br><span class="line"><span class="keyword">char</span>[NUL]</span><br><span class="line"><span class="keyword">byte</span> <span class="number">0</span></span><br><span class="line"><span class="keyword">short</span> <span class="number">0</span></span><br><span class="line"><span class="keyword">int</span> <span class="number">0</span></span><br><span class="line"><span class="keyword">long</span> <span class="number">0</span></span><br><span class="line"><span class="keyword">float</span> <span class="number">0.0</span></span><br><span class="line"><span class="keyword">double</span> <span class="number">0.0</span></span><br><span class="line">reference <span class="keyword">null</span></span><br></pre></td></tr></table></figure>

<p>可见尽管数据成员的初值没有给出，但它们确实有初值（char 值为 0，所以显示为空白）。所以这样至少不会出现”未初始化变量”的风险了。</p>
<p>在类里定义一个对象引用时，如果不将其初始化，那么引用就会被赋值为 <strong>null</strong>。</p>
<h3 id="指定初始化"><a href="#指定初始化" class="headerlink" title="指定初始化"></a>指定初始化</h3><p>怎么给一个变量赋初值呢？一种很直接的方法是在定义类成员变量的地方为其赋值。以下代码修改了 InitialValues 类成员变量的定义，直接提供了初值：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/InitialValues2.java</span></span><br><span class="line"><span class="comment">// Providing explicit initial values</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InitialValues2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">boolean</span> bool = <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">char</span> ch = <span class="string">'x'</span>;</span><br><span class="line">    <span class="keyword">byte</span> b = <span class="number">47</span>;</span><br><span class="line">    <span class="keyword">short</span> s = <span class="number">0xff</span>;</span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">999</span>;</span><br><span class="line">    <span class="keyword">long</span> lng = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">float</span> f = <span class="number">3.14f</span>;</span><br><span class="line">    <span class="keyword">double</span> d = <span class="number">3.14159</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你也可以用同样的方式初始化非基本类型的对象。如果 <strong>Depth</strong> 是一个类，那么可以像下面这样创建一个对象并初始化它：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Measurement.java</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Depth</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Measurement</span> </span>&#123;</span><br><span class="line">    Depth d = <span class="keyword">new</span> Depth();</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果没有为 <strong>d</strong> 赋予初值就尝试使用它，就会出现运行时错误，告诉你产生了一个异常（详细见”异常”章节）。</p>
<p>你也可以通过调用某个方法来提供初值：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/MethodInit.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodInit</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = f();</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">11</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个方法可以带有参数，但这些参数不能是未初始化的类成员变量。因此，可以这么写：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/MethodInit2.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodInit2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = f();</span><br><span class="line">    <span class="keyword">int</span> j = g(i);</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">11</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">g</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> n * <span class="number">10</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是你不能这么写：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/MethodInit3.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodInit3</span> </span>&#123;</span><br><span class="line">    <span class="comment">//- int j = g(i); // Illegal forward reference</span></span><br><span class="line">    <span class="keyword">int</span> i = f();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">11</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">g</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> n * <span class="number">10</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>显然，上述程序的正确性取决于初始化的顺序，而与其编译方式无关。所以，编译器恰当地对”向前引用”发出了警告。</p>
<p>这种初始化方式简单直观，但有个限制：类 <strong>InitialValues</strong> 的每个对象都有相同的初值，有时这的确是我们需要的，但有时却需要更大的灵活性。</p>
<!-- Constructor Initialization -->

<h2 id="构造器初始化"><a href="#构造器初始化" class="headerlink" title="构造器初始化"></a>构造器初始化</h2><p>可以用构造器进行初始化，这种方式给了你更大的灵活性，因为你可以在运行时调用方法进行初始化。但是，这无法阻止自动初始化的进行，他会在构造器被调用之前发生。因此，如果使用如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Counter.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Counter</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">    </span><br><span class="line">    Counter() &#123;</span><br><span class="line">        i = <span class="number">7</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>i</strong> 首先会被初始化为 <strong>0</strong>，然后变为 <strong>7</strong>。对于所有的基本类型和引用，包括在定义时已明确指定初值的变量，这种情况都是成立的。因此，编译器不会强制你一定要在构造器的某个地方或在使用它们之前初始化元素——初始化早已得到了保证。, </p>
<h3 id="初始化的顺序"><a href="#初始化的顺序" class="headerlink" title="初始化的顺序"></a>初始化的顺序</h3><p>在类中变量定义的顺序决定了它们初始化的顺序。即使变量定义散布在方法定义之间，它们仍会在任何方法（包括构造器）被调用之前得到初始化。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/OrderOfInitialization.java</span></span><br><span class="line"><span class="comment">// Demonstrates initialization order</span></span><br><span class="line"><span class="comment">// When the constructor is called to create a</span></span><br><span class="line"><span class="comment">// Window object, you'll see a message:</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Window</span> </span>&#123;</span><br><span class="line">    Window(<span class="keyword">int</span> marker) &#123;</span><br><span class="line">        System.out.println(<span class="string">"Window("</span> + marker + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">House</span> </span>&#123;</span><br><span class="line">    Window w1 = <span class="keyword">new</span> Window(<span class="number">1</span>); <span class="comment">// Before constructor</span></span><br><span class="line"></span><br><span class="line">    House() &#123;</span><br><span class="line">        <span class="comment">// Show that we're in the constructor:</span></span><br><span class="line">        System.out.println(<span class="string">"House()"</span>);</span><br><span class="line">        w3 = <span class="keyword">new</span> Window(<span class="number">33</span>); <span class="comment">// Reinitialize w3</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Window w2 = <span class="keyword">new</span> Window(<span class="number">2</span>); <span class="comment">// After constructor</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"f()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Window w3 = <span class="keyword">new</span> Window(<span class="number">3</span>); <span class="comment">// At end</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OrderOfInitialization</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        House h = <span class="keyword">new</span> House();</span><br><span class="line">        h.f(); <span class="comment">// Shows that construction is done</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Window(1)</span><br><span class="line">Window(2)</span><br><span class="line">Window(3)</span><br><span class="line">House()</span><br><span class="line">Window(33)</span><br><span class="line">f()</span><br></pre></td></tr></table></figure>

<p>在 <strong>House</strong> 类中，故意把几个 <strong>Window</strong> 对象的定义散布在各处，以证明它们全都会在调用构造器或其他方法之前得到初始化。此外，<strong>w3</strong> 在构造器中被再次赋值。</p>
<p>由输出可见，引用 <strong>w3</strong> 被初始化了两次：一次在调用构造器前，一次在构造器调用期间（第一次引用的对象将被丢弃，并作为垃圾回收）。这乍一看可能觉得效率不高，但保证了正确的初始化。试想，如果定义了一个重载构造器，在其中没有初始化 <strong>w3</strong>，同时在定义 <strong>w3</strong> 时没有赋予初值，那会产生怎样的后果呢？</p>
<h3 id="静态数据的初始化"><a href="#静态数据的初始化" class="headerlink" title="静态数据的初始化"></a>静态数据的初始化</h3><p>无论创建多少个对象，静态数据都只占用一份存储区域。<strong>static</strong> 关键字不能应用于局部变量，所以只能作用于属性（字段、域）。如果一个字段是静态的基本类型，你没有初始化它，那么它就会获得基本类型的标准初值。如果它是对象引用，那么它的默认初值就是 <strong>null</strong>。</p>
<p>如果在定义时进行初始化，那么静态变量看起来就跟非静态变量一样。</p>
<p>下面例子显示了静态存储区是何时初始化的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/StaticInitialization.java</span></span><br><span class="line"><span class="comment">// Specifying initial values in a class definition</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bowl</span> </span>&#123;</span><br><span class="line">    Bowl(<span class="keyword">int</span> marker) &#123;</span><br><span class="line">        System.out.println(<span class="string">"Bowl("</span> + marker + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">(<span class="keyword">int</span> marker)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"f1("</span> + marker + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Table</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> Bowl bowl1 = <span class="keyword">new</span> Bowl(<span class="number">1</span>);</span><br><span class="line">    </span><br><span class="line">    Table() &#123;</span><br><span class="line">        System.out.println(<span class="string">"Table()"</span>);</span><br><span class="line">        bowl2.f1(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">(<span class="keyword">int</span> marker)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"f2("</span> + marker + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">static</span> Bowl bowl2 = <span class="keyword">new</span> Bowl(<span class="number">2</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Cupboard</span> </span>&#123;</span><br><span class="line">    Bowl bowl3 = <span class="keyword">new</span> Bowl(<span class="number">3</span>);</span><br><span class="line">    <span class="keyword">static</span> Bowl bowl4 = <span class="keyword">new</span> Bowl(<span class="number">4</span>);</span><br><span class="line">    </span><br><span class="line">    Cupboard() &#123;</span><br><span class="line">        System.out.println(<span class="string">"Cupboard()"</span>);</span><br><span class="line">        bowl4.f1(<span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f3</span><span class="params">(<span class="keyword">int</span> marker)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"f3("</span> + marker + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">static</span> Bowl bowl5 = <span class="keyword">new</span> Bowl(<span class="number">5</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StaticInitialization</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"main creating new Cupboard()"</span>);</span><br><span class="line">        <span class="keyword">new</span> Cupboard();</span><br><span class="line">        System.out.println(<span class="string">"main creating new Cupboard()"</span>);</span><br><span class="line">        <span class="keyword">new</span> Cupboard();</span><br><span class="line">        table.f2(<span class="number">1</span>);</span><br><span class="line">        cupboard.f3(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">static</span> Table table = <span class="keyword">new</span> Table();</span><br><span class="line">    <span class="keyword">static</span> Cupboard cupboard = <span class="keyword">new</span> Cupboard();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">Bowl(1)</span><br><span class="line">Bowl(2)</span><br><span class="line">Table()</span><br><span class="line">f1(1)</span><br><span class="line">Bowl(4)</span><br><span class="line">Bowl(5)</span><br><span class="line">Bowl(3)</span><br><span class="line">Cupboard()</span><br><span class="line">f1(2)</span><br><span class="line">main creating new Cupboard()</span><br><span class="line">Bowl(3)</span><br><span class="line">Cupboard()</span><br><span class="line">f1(2)</span><br><span class="line">main creating new Cupboard()</span><br><span class="line">Bowl(3)</span><br><span class="line">Cupboard()</span><br><span class="line">f1(2)</span><br><span class="line">f2(1)</span><br><span class="line">f3(1)</span><br></pre></td></tr></table></figure>

<p><strong>Bowl</strong> 类展示类的创建，而 <strong>Table</strong> 和 <strong>Cupboard</strong> 在它们的类定义中包含 <strong>Bowl</strong> 类型的静态数据成员。注意，在静态数据成员定义之前，<strong>Cupboard</strong> 类中先定义了一个 <strong>Bowl</strong> 类型的非静态成员 <strong>b3</strong>。</p>
<p>由输出可见，静态初始化只有在必要时刻才会进行。如果不创建 <strong>Table</strong> 对象，也不引用 <strong>Table.bowl1</strong> 或 <strong>Table.bowl2</strong>，那么静态的 <strong>Bowl</strong> 类对象 <strong>bowl1</strong> 和 <strong>bowl2</strong> 永远不会被创建。只有在第一个 Table 对象被创建（或被访问）时，它们才会被初始化。此后，静态对象不会再次被初始化。</p>
<p>初始化的顺序先是静态对象（如果它们之前没有被初始化的话），然后是非静态对象，从输出中可以看出。要执行 <code>main()</code> 方法，必须加载 <strong>StaticInitialization</strong> 类，它的静态属性 <strong>table</strong> 和 <strong>cupboard</strong> 随后被初始化，这会导致它们对应的类也被加载，而由于它们都包含静态的 <strong>Bowl</strong> 对象，所以 <strong>Bowl</strong> 类也会被加载。因此，在这个特殊的程序中，所有的类都会在 <code>main()</code> 方法之前被加载。实际情况通常并非如此，因为在典型的程序中，不会像本例中所示的那样，将所有事物通过 <strong>static</strong> 联系起来。</p>
<p>概括一下创建对象的过程，假设有个名为 <strong>Dog</strong> 的类：</p>
<ol>
<li>即使没有显式地使用 <strong>static</strong> 关键字，构造器实际上也是静态方法。所以，当首次创建 <strong>Dog</strong> 类型的对象或是首次访问 <strong>Dog</strong> 类的静态方法或属性时，Java 解释器必须在类路径中查找，以定位 <strong>Dog.class</strong>。</li>
<li>当加载完 <strong>Dog.class</strong> 后（后面会学到，这将创建一个 <strong>Class</strong> 对象），有关静态初始化的所有动作都会执行。因此，静态初始化只会在首次加载 <strong>Class</strong> 对象时初始化一次。</li>
<li>当用 <code>new Dog()</code> 创建对象时，首先会在堆上为 <strong>Dog</strong> 对象分配足够的存储空间。</li>
<li>分配的存储空间首先会被清零，即会将 <strong>Dog</strong> 对象中的所有基本类型数据设置为默认值（数字会被置为 0，布尔型和字符型也相同），引用被置为 <strong>null</strong>。</li>
<li>执行所有出现在字段定义处的初始化动作。</li>
<li>执行构造器。你将会在”复用”这一章看到，这可能会牵涉到很多动作，尤其当涉及继承的时候。</li>
</ol>
<h3 id="显式的静态初始化"><a href="#显式的静态初始化" class="headerlink" title="显式的静态初始化"></a>显式的静态初始化</h3><p>你可以将一组静态初始化动作放在类里面一个特殊的”静态子句”（有时叫做静态块）中。像下面这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Spoon.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Spoon</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> i;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        i = <span class="number">47</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这看起来像个方法，但实际上它只是一段跟在 <strong>static</strong> 关键字后面的代码块。与其他静态初始化动作一样，这段代码仅执行一次：当首次创建这个类的对象或首次访问这个类的静态成员（甚至不需要创建该类的对象）时。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/ExplicitStatic.java</span></span><br><span class="line"><span class="comment">// Explicit static initialization with "static" clause</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Cup</span> </span>&#123;</span><br><span class="line">    Cup(<span class="keyword">int</span> marker) &#123;</span><br><span class="line">        System.out.println(<span class="string">"Cup("</span> + marker + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">int</span> marker)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"f("</span> + marker + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Cups</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> Cup cup1;</span><br><span class="line">    <span class="keyword">static</span> Cup cup2;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        cup1 = <span class="keyword">new</span> Cup(<span class="number">1</span>);</span><br><span class="line">        cup2 = <span class="keyword">new</span> Cup(<span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    Cups() &#123;</span><br><span class="line">        System.out.println(<span class="string">"Cups()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExplicitStatic</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Inside main()"</span>);</span><br><span class="line">        Cups.cup1.f(<span class="number">99</span>); <span class="comment">// [1]</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// static Cups cups1 = new Cups(); // [2]</span></span><br><span class="line">    <span class="comment">// static Cups cups2 = new Cups(); // [2]</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Inside main</span><br><span class="line">Cup(1)</span><br><span class="line">Cup(2)</span><br><span class="line">f(99)</span><br></pre></td></tr></table></figure>

<p>无论是通过标为 [1] 的行访问静态的 <strong>cup1</strong> 对象，还是把标为 [1] 的行去掉，让它去运行标为 [2] 的那行代码（去掉  [2] 的注释），<strong>Cups</strong> 的静态初始化动作都会执行。如果同时注释 [1] 和 [2] 处，那么 <strong>Cups</strong> 的静态初始化就不会进行。此外，把标为 [2] 处的注释都去掉还是只去掉一个，静态初始化只会执行一次。</p>
<h3 id="非静态实例初始化"><a href="#非静态实例初始化" class="headerlink" title="非静态实例初始化"></a>非静态实例初始化</h3><p>Java 提供了被称为<em>实例初始化</em>的类似语法，用来初始化每个对象的非静态变量，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Mugs.java</span></span><br><span class="line"><span class="comment">// Instance initialization</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Mug</span> </span>&#123;</span><br><span class="line">    Mug(<span class="keyword">int</span> marker) &#123;</span><br><span class="line">        System.out.println(<span class="string">"Mug("</span> + marker + <span class="string">")"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Mugs</span> </span>&#123;</span><br><span class="line">    Mug mug1;</span><br><span class="line">    Mug mug2;</span><br><span class="line">    &#123; <span class="comment">// [1]</span></span><br><span class="line">        mug1 = <span class="keyword">new</span> Mug(<span class="number">1</span>);</span><br><span class="line">        mug2 = <span class="keyword">new</span> Mug(<span class="number">2</span>);</span><br><span class="line">        System.out.println(<span class="string">"mug1 &amp; mug2 initialized"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    Mugs() &#123;</span><br><span class="line">        System.out.println(<span class="string">"Mugs()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    Mugs(<span class="keyword">int</span> i) &#123;</span><br><span class="line">        System.out.println(<span class="string">"Mugs(int)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Inside main()"</span>);</span><br><span class="line">        <span class="keyword">new</span> Mugs();</span><br><span class="line">        System.out.println(<span class="string">"new Mugs() completed"</span>);</span><br><span class="line">        <span class="keyword">new</span> Mugs(<span class="number">1</span>);</span><br><span class="line">        System.out.println(<span class="string">"new Mugs(1) completed"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Inside main</span><br><span class="line">Mug(1)</span><br><span class="line">Mug(2)</span><br><span class="line">mug1 &amp; mug2 initialized</span><br><span class="line">Mugs()</span><br><span class="line">new Mugs() completed</span><br><span class="line">Mug(1)</span><br><span class="line">Mug(2)</span><br><span class="line">mug1 &amp; mug2 initialized</span><br><span class="line">Mugs(int)</span><br><span class="line">new Mugs(1) completed</span><br></pre></td></tr></table></figure>

<p>看起来它很像静态代码块，只不过少了 <strong>static</strong> 关键字。这种语法对于支持”匿名内部类”（参见”内部类”一章）的初始化是必须的，但是你也可以使用它保证某些操作一定会发生，而不管哪个构造器被调用。从输出看出，实例初始化子句是在两个构造器之前执行的。</p>
<!-- Array Initialization -->

<h2 id="数组初始化"><a href="#数组初始化" class="headerlink" title="数组初始化"></a>数组初始化</h2><p>数组是相同类型的、用一个标识符名称封装到一起的一个对象序列或基本类型数据序列。数组是通过方括号下标操作符 [] 来定义和使用的。要定义一个数组引用，只需要在类型名加上方括号：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span>[] a1;</span><br></pre></td></tr></table></figure>

<p>方括号也可放在标识符的后面，两者的含义是一样的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a1[];</span><br></pre></td></tr></table></figure>

<p>这种格式符合 C 和 C++ 程序员的习惯。不过前一种格式或许更合理，毕竟它表明类型是”一个 <strong>int</strong> 型数组”。本书中采用这种格式。</p>
<p>编译器不允许指定数组的大小。这又把我们带回有关”引用”的问题上。你所拥有的只是对数组的一个引用（你已经为该引用分配了足够的存储空间），但是还没有给数组对象本身分配任何空间。为了给数组创建相应的存储空间，必须写初始化表达式。对于数组，初始化动作可以出现在代码的任何地方，但是也可以使用一种特殊的初始化表达式，它必须在创建数组的地方出现。这种特殊的初始化是由一对花括号括起来的值组成。这种情况下，存储空间的分配（相当于使用 <strong>new</strong>） 将由编译器负责。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span>[] a1 = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;;</span><br></pre></td></tr></table></figure>

<p>那么为什么在还没有数组的时候定义一个数组引用呢？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span>[] a2;</span><br></pre></td></tr></table></figure>

<p>在 Java 中可以将一个数组赋值给另一个数组，所以可以这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a2 = a1;</span><br></pre></td></tr></table></figure>

<p>其实真正做的只是复制了一个引用，就像下面演示的这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/ArraysOfPrimitives.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ArraysOfPrimitives</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span>[] a1 = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;;</span><br><span class="line">        <span class="keyword">int</span>[] a2;</span><br><span class="line">        a2 = a1;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; a2.length; i++) &#123;</span><br><span class="line">            a2[i] += <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; a1.length; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">"a1["</span> + i + <span class="string">"] = "</span> + a1[i]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a1[0] &#x3D; 2;</span><br><span class="line">a1[1] &#x3D; 3;</span><br><span class="line">a1[2] &#x3D; 4;</span><br><span class="line">a1[3] &#x3D; 5;</span><br><span class="line">a1[4] &#x3D; 6;</span><br></pre></td></tr></table></figure>

<p><strong>a1</strong> 初始化了，但是 <strong>a2</strong> 没有；这里，<strong>a2</strong> 在后面被赋给另一个数组。由于 <strong>a1</strong> 和 <strong>a2</strong> 是相同数组的别名，因此通过 <strong>a2</strong> 所做的修改在 <strong>a1</strong> 中也能看到。</p>
<p>所有的数组（无论是对象数组还是基本类型数组）都有一个固定成员 <strong>length</strong>，告诉你这个数组有多少个元素，你不能对其修改。与 C 和 C++ 类似，Java 数组计数也是从 0 开始的，所能使用的最大下标数是 <strong>length - 1</strong>。超过这个边界，C 和 C++ 会默认接受，允许你访问所有内存，许多声名狼藉的 bug 都是由此而生。但是 Java 在你访问超出这个边界时，会报运行时错误（异常），从而避免此类问题。</p>
<h3 id="动态数组创建"><a href="#动态数组创建" class="headerlink" title="动态数组创建"></a>动态数组创建</h3><p>如果在编写程序时，不确定数组中需要多少个元素，可以使用 <strong>new</strong> 在数组中创建元素。如下例所示，使用 <strong>new</strong> 创建基本类型数组。<strong>new</strong> 不能创建非数组以外的基本类型数据：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/ArrayNew.java</span></span><br><span class="line"><span class="comment">// Creating arrays with new</span></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ArrayNew</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span>[] a;</span><br><span class="line">        Random rand = <span class="keyword">new</span> Random(<span class="number">47</span>);</span><br><span class="line">        a = <span class="keyword">new</span> <span class="keyword">int</span>[rand.nextInt(<span class="number">20</span>)];</span><br><span class="line">        System.out.println(<span class="string">"length of a = "</span> + a.length);</span><br><span class="line">        System.out.println(Arrays.toString(a));</span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">length of a &#x3D; 18</span><br><span class="line">[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]</span><br></pre></td></tr></table></figure>

<p>数组的大小是通过 <code>Random.nextInt()</code> 随机确定的，这个方法会返回 0 到输入参数之间的一个值。 由于随机性，很明显数组的创建确实是在运行时进行的。此外，程序输出表明，数组元素中的基本数据类型值会自动初始化为默认值（对于数字和字符是 0；对于布尔型是 <strong>false</strong>）。<code>Arrays.toString()</code> 是 <strong>java.util</strong> 标准类库中的方法，会产生一维数组的可打印版本。</p>
<p>本例中，数组也可以在定义的同时进行初始化：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span>[] a = <span class="keyword">new</span> <span class="keyword">int</span>[rand.nextInt(<span class="number">20</span>)];</span><br></pre></td></tr></table></figure>

<p>如果可能的话，应该尽量这么做。</p>
<p>如果你创建了一个非基本类型的数组，那么你创建的是一个引用数组。以整型的包装类型 <strong>Integer</strong> 为例，它是一个类而非基本类型：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/ArrayClassObj.java</span></span><br><span class="line"><span class="comment">// Creating an array of nonprimitive objects</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ArrayClassObj</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Random rand = <span class="keyword">new</span> Random(<span class="number">47</span>);</span><br><span class="line">        Integer[] a = <span class="keyword">new</span> Integer[rand.nextInt(<span class="number">20</span>)];</span><br><span class="line">        System.out.println(<span class="string">"length of a = "</span> + a.length);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; a.length; i++) &#123;</span><br><span class="line">            a[i] = rand.nextInt(<span class="number">500</span>); <span class="comment">// Autoboxing</span></span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(Arrays.toString(a));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">length of a &#x3D; 18</span><br><span class="line">[55, 193, 361, 461, 429, 368, 200, 22, 207, 288, 128, 51, 89, 309, 278, 498, 361, 20]</span><br></pre></td></tr></table></figure>

<p>这里，即使使用 new 创建数组之后：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Integer[] a = <span class="keyword">new</span> Integer[rand.nextInt(<span class="number">20</span>)];</span><br></pre></td></tr></table></figure>

<p>它只是一个引用数组，直到通过创建新的 <strong>Integer</strong> 对象（通过自动装箱），并把对象赋值给引用，初始化才算结束：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a[i] = rand.nextInt(<span class="number">500</span>);</span><br></pre></td></tr></table></figure>

<p>如果忘记了创建对象，但试图使用数组中的空引用，就会在运行时产生异常。</p>
<p>也可以用花括号括起来的列表来初始化数组，有两种形式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/ArrayInit.java</span></span><br><span class="line"><span class="comment">// Array initialization</span></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ArrayInit</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Integer[] a = &#123;</span><br><span class="line">                <span class="number">1</span>, <span class="number">2</span>,</span><br><span class="line">                <span class="number">3</span>, <span class="comment">// Autoboxing</span></span><br><span class="line">        &#125;;</span><br><span class="line">        Integer[] b = <span class="keyword">new</span> Integer[] &#123;</span><br><span class="line">                <span class="number">1</span>, <span class="number">2</span>,</span><br><span class="line">                <span class="number">3</span>, <span class="comment">// Autoboxing</span></span><br><span class="line">        &#125;;</span><br><span class="line">        System.out.println(Arrays.toString(a));</span><br><span class="line">        System.out.println(Arrays.toString(b));</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[1, 2, 3]</span><br><span class="line">[1, 2, 3]</span><br></pre></td></tr></table></figure>

<p>在这两种形式中，初始化列表的最后一个逗号是可选的（这一特性使维护长列表变得更容易）。</p>
<p>尽管第一种形式很有用，但是它更加受限，因为它只能用于数组定义处。第二种和第三种形式可以用在任何地方，甚至用在方法的内部。例如，你创建了一个 <strong>String</strong> 数组，将其传递给另一个类的 <code>main()</code> 方法，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/DynamicArray.java</span></span><br><span class="line"><span class="comment">// Array initialization</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicArray</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Other.main(<span class="keyword">new</span> String[] &#123;<span class="string">"fiddle"</span>, <span class="string">"de"</span>, <span class="string">"dum"</span>&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Other</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (String s: args) &#123;</span><br><span class="line">            System.out.print(s + <span class="string">" "</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fiddle de dum</span><br></pre></td></tr></table></figure>

<p><code>Other.main()</code> 的参数是在调用处创建的，因此你甚至可以在方法调用处提供可替换的参数。</p>
<h3 id="可变参数列表"><a href="#可变参数列表" class="headerlink" title="可变参数列表"></a>可变参数列表</h3><p>你可以以一种类似 C 语言中的可变参数列表（C 通常把它称为”varargs”）来创建和调用方法。这可以应用在参数个数或类型未知的场合。由于所有的类都最后继承于 <strong>Object</strong> 类（随着本书的进展，你会对此有更深的认识），所以你可以创建一个以 Object 数组为参数的方法，并像下面这样调用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/VarArgs.java</span></span><br><span class="line"><span class="comment">// Using array syntax to create variable argument lists</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VarArgs</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printArray</span><span class="params">(Object[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (Object obj: args) &#123;</span><br><span class="line">            System.out.print(obj + <span class="string">" "</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        printArray(<span class="keyword">new</span> Object[] &#123;<span class="number">47</span>, (<span class="keyword">float</span>) <span class="number">3.14</span>, <span class="number">11.11</span>&#125;);</span><br><span class="line">        printArray(<span class="keyword">new</span> Object[] &#123;<span class="string">"one"</span>, <span class="string">"two"</span>, <span class="string">"three"</span>&#125;);</span><br><span class="line">        printArray(<span class="keyword">new</span> Object[] &#123;<span class="keyword">new</span> A(), <span class="keyword">new</span> A(), <span class="keyword">new</span> A()&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">47 3.14 11.11 </span><br><span class="line">one two three </span><br><span class="line">A@15db9742 A@6d06d69c A@7852e922</span><br></pre></td></tr></table></figure>

<p><code>printArray()</code> 的参数是 <strong>Object</strong> 数组，使用 for-in 语法遍历和打印数组的每一项。标准 Java 库能输出有意义的内容，但这里创建的是类的对象，打印出的内容是类名，后面跟着一个 <strong>@</strong> 符号以及多个十六进制数字。因而，默认行为（如果没有定义 <code>toString()</code> 方法的话，后面会讲这个方法）就是打印类名和对象的地址。</p>
<p>你可能看到像上面这样编写的 Java 5 之前的代码，它们可以产生可变的参数列表。在 Java 5 中，这种期盼已久的特性终于添加了进来，就像在 <code>printArray()</code> 中看到的那样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/NewVarArgs.java</span></span><br><span class="line"><span class="comment">// Using array syntax to create variable argument lists</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NewVarArgs</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printArray</span><span class="params">(Object... args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (Object obj: args) &#123;</span><br><span class="line">            System.out.print(obj + <span class="string">" "</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// Can take individual elements:</span></span><br><span class="line">        printArray(<span class="number">47</span>, (<span class="keyword">float</span>) <span class="number">3.14</span>, <span class="number">11.11</span>);</span><br><span class="line">        printArray(<span class="number">47</span>, <span class="number">3.14F</span>, <span class="number">11.11</span>);</span><br><span class="line">        printArray(<span class="string">"one"</span>, <span class="string">"two"</span>, <span class="string">"three"</span>);</span><br><span class="line">        printArray(<span class="keyword">new</span> A(), <span class="keyword">new</span> A(), <span class="keyword">new</span> A());</span><br><span class="line">        <span class="comment">// Or an array:</span></span><br><span class="line">        printArray((Object[]) <span class="keyword">new</span> Integer[] &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;);</span><br><span class="line">        printArray(); <span class="comment">// Empty list is OK</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">47 3.14 11.11 </span><br><span class="line">47 3.14 11.11 </span><br><span class="line">one two three </span><br><span class="line">A@15db9742 A@6d06d69c A@7852e922 </span><br><span class="line">1 2 3 4</span><br></pre></td></tr></table></figure>

<p>有了可变参数，你就再也不用显式地编写数组语法了，当你指定参数时，编译器实际上会为你填充数组。你获取的仍然是一个数组，这就是为什么 <code>printArray()</code> 可以使用 for-in 迭代数组的原因。但是，这不仅仅只是从元素列表到数组的自动转换。注意程序的倒数第二行，一个 <strong>Integer</strong> 数组（通过自动装箱创建）被转型为一个 <strong>Object</strong> 数组（为了移除编译器的警告），并且传递给了 <code>printArray()</code>。显然，编译器会发现这是一个数组，不会执行转换。因此，如果你有一组事物，可以把它们当作列表传递，而如果你已经有了一个数组，该方法会把它们当作可变参数列表来接受。</p>
<p>程序的最后一行表明，可变参数的个数可以为 0。当具有可选的尾随参数时，这一特性会有帮助：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/OptionalTrailingArguments.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OptionalTrailingArguments</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">int</span> required, String... trailing)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"required: "</span> + required + <span class="string">" "</span>);</span><br><span class="line">        <span class="keyword">for</span> (String s: trailing) &#123;</span><br><span class="line">            System.out.print(s + <span class="string">" "</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        f(<span class="number">1</span>, <span class="string">"one"</span>);</span><br><span class="line">        f(<span class="number">2</span>, <span class="string">"two"</span>, <span class="string">"three"</span>);</span><br><span class="line">        f(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">required: 1 one </span><br><span class="line">required: 2 two three </span><br><span class="line">required: 0</span><br></pre></td></tr></table></figure>

<p>这段程序展示了如何使用除了 <strong>Object</strong> 类之外类型的可变参数列表。这里，所有的可变参数都是 <strong>String</strong> 对象。可变参数列表中可以使用任何类型的参数，包括基本类型。下面例子展示了可变参数列表变为数组的情形，并且如果列表中没有任何元素，那么转变为大小为 0 的数组：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/VarargType.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VarargType</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(Character... args)</span> </span>&#123;</span><br><span class="line">        System.out.print(args.getClass());</span><br><span class="line">        System.out.println(<span class="string">" length "</span> + args.length);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">g</span><span class="params">(<span class="keyword">int</span>... args)</span> </span>&#123;</span><br><span class="line">        System.out.print(args.getClass());</span><br><span class="line">        System.out.println(<span class="string">" length "</span> + args.length)</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        f(<span class="string">'a'</span>);</span><br><span class="line">        f();</span><br><span class="line">        g(<span class="number">1</span>);</span><br><span class="line">        g();</span><br><span class="line">        System.out.println(<span class="string">"int[]: "</span>+ <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">0</span>].getClass());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">class [Ljava.lang.Character; length 1</span><br><span class="line">class [Ljava.lang.Character; length 0</span><br><span class="line">class [I length 1</span><br><span class="line">class [I length 0</span><br><span class="line">int[]: class [I</span><br></pre></td></tr></table></figure>

<p><code>getClass()</code> 方法属于 Object 类，将在”类型信息”一章中全面介绍。它会产生对象的类，并在打印该类时，看到表示该类类型的编码字符串。前导的 <strong>[</strong> 代表这是一个后面紧随的类型的数组，<strong>I</strong> 表示基本类型 <strong>int</strong>；为了进行双重检查，我在最后一行创建了一个 <strong>int</strong> 数组，打印了其类型。这样也验证了使用可变参数列表不依赖于自动装箱，而使用的是基本类型。</p>
<p>然而，可变参数列表与自动装箱可以和谐共处，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/AutoboxingVarargs.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AutoboxingVarargs</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(Integer... args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (Integer i: args) &#123;</span><br><span class="line">            System.out.print(i + <span class="string">" "</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        f(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line">        f(<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>);</span><br><span class="line">        f(<span class="number">10</span>, <span class="number">11</span>, <span class="number">12</span>);</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1 2</span><br><span class="line">4 5 6 7 8 9</span><br><span class="line">10 11 12</span><br></pre></td></tr></table></figure>

<p>注意吗，你可以在单个参数列表中将类型混合在一起，自动装箱机制会有选择地把 <strong>int</strong> 类型的参数提升为 <strong>Integer</strong>。</p>
<p>可变参数列表使得方法重载更加复杂了，尽管乍看之下似乎足够安全：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/OverloadingVarargs.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OverloadingVarargs</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(Character... args)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"first"</span>);</span><br><span class="line">        <span class="keyword">for</span> (Character c: args) &#123;</span><br><span class="line">            System.out.print(<span class="string">" "</span> + c);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(Integer... args)</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"second"</span>);</span><br><span class="line">        <span class="keyword">for</span> (Integer i: args) &#123;</span><br><span class="line">            System.out.print(<span class="string">" "</span> + i);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(Long... args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"third"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        f(<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>);</span><br><span class="line">        f(<span class="number">1</span>);</span><br><span class="line">        f(<span class="number">2</span>, <span class="number">1</span>);</span><br><span class="line">        f(<span class="number">0</span>);</span><br><span class="line">        f(<span class="number">0L</span>);</span><br><span class="line">        <span class="comment">//- f(); // Won's compile -- ambiguous</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">first a b c</span><br><span class="line">second 1</span><br><span class="line">second 2 1</span><br><span class="line">second 0</span><br><span class="line">third</span><br></pre></td></tr></table></figure>

<p>在每种情况下，编译器都会使用自动装箱来匹配重载的方法，然后调用最明确匹配的方法。</p>
<p>但是如果调用不含参数的 <code>f()</code>，编译器就无法知道应该调用哪个方法了。尽管这个错误可以弄清楚，但是它可能会使客户端程序员感到意外。</p>
<p>你可能会通过在某个方法中增加一个非可变参数解决这个问题：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/OverloadingVarargs2.java</span></span><br><span class="line"><span class="comment">// &#123;WillNotCompile&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OverloadingVarargs2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">float</span> i, Character... args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"first"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(Character... args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"second"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        f(<span class="number">1</span>, <span class="string">'a'</span>);</span><br><span class="line">        f(<span class="string">'a'</span>, <span class="string">'b'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>{WillNotCompile}</strong> 注释把该文件排除在了本书的 Gradle 构建之外。如果你手动编译它，会得到下面的错误信息：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">OverloadingVarargs2.java:14:error:reference to f is ambiguous f(&#39;a&#39;, &#39;b&#39;);</span><br><span class="line">\^</span><br><span class="line">both method f(float, Character...) in OverloadingVarargs2 and method f(Character...) in OverloadingVarargs2 match 1 error</span><br></pre></td></tr></table></figure>

<p>如果你给这两个方法都添加一个非可变参数，就可以解决问题了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/OverloadingVarargs3</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OverloadingVarargs3</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">float</span> i, Character... args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"first"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">char</span> c, Character... args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"second"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        f(<span class="number">1</span>, <span class="string">'a'</span>);</span><br><span class="line">        f(<span class="string">'a'</span>, <span class="string">'b'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">first</span><br><span class="line">second</span><br></pre></td></tr></table></figure>

<p>你应该总是在重载方法的一个版本上使用可变参数列表，或者压根不用它。</p>
<!-- Enumerated Types -->

<h2 id="枚举类型"><a href="#枚举类型" class="headerlink" title="枚举类型"></a>枚举类型</h2><p>Java 5 中添加了一个看似很小的特性 <strong>enum</strong> 关键字，它使得我们在需要群组并使用枚举类型集时，可以很方便地处理。以前，你需要创建一个整数常量集，但是这些值并不会将自身限制在这个常量集的范围内，因此使用它们更有风险，而且更难使用。枚举类型属于非常普遍的需求，C、C++ 和其他许多语言都已经拥有它了。在 Java 5 之前，Java 程序员必须了解许多细节并格外仔细地去达成 <strong>enum</strong> 的效果。现在 Java 也有了 <strong>enum</strong>，并且它的功能比 C/C++ 中的完备得多。下面是个简单的例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Spiciness.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> Spiciness &#123;</span><br><span class="line">    NOT, MILD, MEDIUM, HOT, FLAMING</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里创建了一个名为 <strong>Spiciness</strong> 的枚举类型，它有5个值。由于枚举类型的实例是常量，因此按照命名惯例，它们都用大写字母表示（如果名称中含有多个单词，使用下划线分隔）。</p>
<p>要使用 <strong>enum</strong>，需要创建一个该类型的引用，然后将其赋值给某个实例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/SimpleEnumUse.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleEnumUse</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Spiciness howHot = Spiciness.MEDIUM;</span><br><span class="line">        System.out.println(howHot);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">MEDIUM</span><br></pre></td></tr></table></figure>

<p>在你创建 <strong>enum</strong> 时，编译器会自动添加一些有用的特性。例如，它会创建 <code>toString()</code> 方法，以便你方便地显示某个 <strong>enum</strong> 实例的名称，这从上面例子中的输出可以看出。编译器还会创建 <code>ordinal()</code> 方法表示某个特定 <strong>enum</strong> 常量的声明顺序，<code>static values()</code> 方法按照 enum 常量的声明顺序，生成这些常量值构成的数组：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/EnumOrder.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EnumOrder</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (Spiciness s: Spiciness.values()) &#123;</span><br><span class="line">            System.out.println(s + <span class="string">", ordinal "</span> + s.ordinal());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">NOT, ordinal 0</span><br><span class="line">MILD, ordinal 1</span><br><span class="line">MEDIUM, ordinal 2</span><br><span class="line">HOT, ordinal 3</span><br><span class="line">FLAMING, ordinal 4</span><br></pre></td></tr></table></figure>

<p>尽管 <strong>enum</strong> 看起来像是一种新的数据类型，但是这个关键字只是在生成 <strong>enum</strong> 的类时，产生了某些编译器行为，因此在很大程度上你可以将 <strong>enum</strong> 当作其他任何类。事实上，<strong>enum</strong> 确实是类，并且具有自己的方法。</p>
<p><strong>enum</strong> 有一个很实用的特性，就是在 <strong>switch</strong> 语句中使用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// housekeeping/Burrito.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Burrito</span> </span>&#123;</span><br><span class="line">    Spiciness degree;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Burrito</span><span class="params">(Spiciness degree)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.degree = degree;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">describe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"This burrito is "</span>);</span><br><span class="line">        <span class="keyword">switch</span>(degree) &#123;</span><br><span class="line">            <span class="keyword">case</span> NOT:</span><br><span class="line">                System.out.println(<span class="string">"not spicy at all."</span>);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MILD:</span><br><span class="line">            <span class="keyword">case</span> MEDIUM:</span><br><span class="line">                System.out.println(<span class="string">"a little hot."</span>);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> HOT:</span><br><span class="line">            <span class="keyword">case</span> FLAMING:</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                System.out.println(<span class="string">"maybe too hot"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Burrito plain = <span class="keyword">new</span> Burrito(Spiciness.NOT),</span><br><span class="line">        greenChile = <span class="keyword">new</span> Burrito(Spiciness.MEDIUM),</span><br><span class="line">        jalapeno = <span class="keyword">new</span> Burrito(Spiciness.HOT);</span><br><span class="line">        plain.describe();</span><br><span class="line">        greenChile.describe();</span><br><span class="line">        jalapeno.describe();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">This burrito is not spicy at all.</span><br><span class="line">This burrito is a little hot.</span><br><span class="line">This burrito is maybe too hot.</span><br></pre></td></tr></table></figure>

<p>由于 <strong>switch</strong> 是在有限的可能值集合中选择，因此它与 <strong>enum</strong> 是绝佳的组合。注意，enum 的名称是如何能够倍加清楚地表明程序的目的的。</p>
<p>通常，你可以将 <strong>enum</strong> 用作另一种创建数据类型的方式，然后使用所得到的类型。这正是关键所在，所以你不用过多地考虑它们。在 <strong>enum</strong> 被引入之前，你必须花费大量的精力去创建一个等同的枚举类型，并是安全可用的。</p>
<p>这些介绍对于你理解和使用基本的 <strong>enum</strong> 已经足够了，我们会在”枚举”一章中进行更深入的探讨。</p>
<!-- Summary -->

<h2 id="本章小结"><a href="#本章小结" class="headerlink" title="本章小结"></a>本章小结</h2><p>构造器，这种看起来精巧的初始化机制，应该给了你很强的暗示：初始化在编程语言中的重要地位。C++ 的发明者 Bjarne Stroustrup 在设计 C++ 期间，在针对 C 语言的生产效率进行的最初调查中发现，错误的初始化会导致大量编程错误。这些错误很难被发现，同样，不合理的清理也会如此。因为构造器能保证进行正确的初始化和清理（没有正确的构造器调用，编译器就不允许创建对象），所以你就有了完全的控制和安全。</p>
<p>在 C++ 中，析构器很重要，因为用 <strong>new</strong> 创建的对象必须被明确地销毁。在 Java 中，垃圾回收器会自动地释放所有对象的内存，所以很多时候类似的清理方法就不太需要了（但是当要用到的时候，你得自己动手）。在不需要类似析构器行为的时候，Java 的垃圾回收器极大地简化了编程，并加强了内存管理上的安全性。一些垃圾回收器甚至能清理其他资源，如图形和文件句柄。然而，垃圾回收器确实增加了运行时开销，由于 Java 解释器从一开始就很慢，所以这种开销到底造成多大的影响很难看出来。随着时间的推移，Java 在性能方面提升了很多，但是速度问题仍然是它涉足某些特定编程领域的障碍。</p>
<p>由于要保证所有对象被创建，实际上构造器比这里讨论得更加复杂。特别是当通过<em>组合</em>或<em>继承</em>创建新类的时候，这种保证仍然成立，并且需要一些额外的语法来支持。在后面的章节中，你会学习组合，继承以及它们如何影响构造器。</p>
<!-- 分页 -->

<div style="page-break-after: always;"></div>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://yoursite.com/2020/07/27/%E7%AC%AC%E5%85%AD%E7%AB%A0%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%92%8C%E6%B8%85%E7%90%86/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/" rel="tag">Java编程思想</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/OnJava8/" rel="tag">OnJava8</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/07/28/%E7%AC%AC%E4%B8%83%E7%AB%A0%20%E5%B0%81%E8%A3%85/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            第七章 封装
          
        </div>
      </a>
    
    
      <a href="/2020/07/26/%E7%AC%AC%E4%BA%94%E7%AB%A0%20%E6%8E%A7%E5%88%B6%E6%B5%81/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">第五章 控制流</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> Gghui
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="歆雨小屋"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=371362&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
  </div>
</body>

</html>